<template>
  <view class="uni-container">
    <uni-forms ref="form" v-model="formData" :rules="rules" validateTrigger="bind">
      <uni-forms-item name="course_id" label="课程编码">
  <uni-easyinput placeholder="课程编码 不允许重复" v-model="formData.course_id" />
</uni-forms-item>
<uni-forms-item name="course_name" label="课程名">
  <uni-easyinput placeholder="课程名" v-model="formData.course_name" />
</uni-forms-item>
<!-- <uni-forms-item name="year" label="年份">
  <uni-easyinput placeholder="年份" type="number" v-model="formData.year" />
</uni-forms-item> -->
<uni-forms-item name="credit" label="学分">
  <uni-easyinput placeholder="学分" type="number" v-model="formData.credit" />
</uni-forms-item>
<!-- <uni-forms-item name="term" label="学期">
  <uni-data-checkbox v-model="formData.term" :localdata="formOptions.term_localdata" />
</uni-forms-item> -->
<uni-forms-item name="college" label="学院">
  <uni-data-checkbox v-model="formData.college" collection="hr-college" field="college_id as value, college_name as text" />
</uni-forms-item>
<!-- <uni-forms-item name="prerequisite" label="先修课程">
  <uni-easyinput placeholder="先修课程编码Id" v-model="formData.prerequisite" @blur="nameChange" />
</uni-forms-item>
<uni-forms-item name="prerequisite_name" label="先修课程名称">
  <uni-easyinput placeholder="先修课程名称" v-model="formData.prerequisite_name" :disabled=true />
</uni-forms-item> -->
<uni-forms-item name="status" label="状态" v-if="$hasRole('admin')">
  <uni-data-checkbox v-model="formData.status" :localdata="formOptions.status_localdata"  />
</uni-forms-item>
<uni-forms-item name="comment" label="简介">
  <textarea @input="binddata('comment', $event.detail.value)" class="uni-textarea-border" :value="formData.comment"></textarea>
</uni-forms-item>
<uni-forms-item name="exam" label="考试">
  <uni-data-checkbox v-model="formData.exam" :localdata="formOptions.exam_localdata" />
</uni-forms-item>

      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator url="/pages/course/code/list" style="margin-left: 15px;">
            <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import validator from '@/js_sdk/validator/course.js';
	var year = new Date().getFullYear() // 当前年份
	var term = new Date().getMonth()+1 < 6 ? 0 : 1 // 划分为上半年和下半年
  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'hr-course';

  function getValidator(fields) {
    let reuslt = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        reuslt[key] = validator[key]
      }
    }
    return reuslt
  }

  export default {
    data() {
      return {
        formOptions: {
		  "term_localdata": [
			{
			  "text": "上学期",
			  "value": 0
			},
			{
			  "text": "下学期",
			  "value": 1
			}
		  ],
		  "status_localdata": [
			{
			  "text": "正常",
			  "value": 0
			},
			{
			  "text": "禁用",
			  "value": 1
			}
		  ],
		  "exam_localdata": [
			{
			  "text": "考试课",
			  "value": 0
			},
			{
			  "text": "考查课",
			  "value": 1
			},
			{
			  "text": "在线课",
			  "value": 2
			}
		  ]
		},
    formData: {
		  course_id: "",
		  course_name: "",
		  year: null,
		  credit: 2,
		  term: null,
		  college: -1,
		  prerequisite: "",
		  prerequisite_name: "",
		  status: 0,
		  comment: "",
		  exam: 0
		},
        rules: {
          ...getValidator(["course","course_name","year","credit","term","prerequisite","prerequisite_name","status","comment","exam","college"])
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
	watch:{
		"formData.prerequisite_name"(newValue,oldValue){
			console.info(newValue)
		}
	},
    methods: {
      /**
       * 触发表单提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.submit().then((res) => {
          this.submitForm(res)
        }).catch((errors) => {
          uni.hideLoading()
        })
      },

      submitForm(value) {
				value.year = year // 当前年份
				value.term = term // 划分为上半年和下半年
        // 使用 uni-clientDB 提交数据
        db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateTo({
				url: '/pages/course/code/list'
			}), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      },
	  nameChange(e){
		  let { value } = e.detail
		  if(value != ""){
			  db.collection(dbCollectionName).where({
			  	course_id : value
			  }).get().then((res) => {
					if(res.result.data == ''){
						uni.showModal({
							content: '没有找到此课程',
							showCancel: false
						})
					}else{
						let data = res.result.data[0].course_name
						this.formData.prerequisite_name = data
					}
			  }).catch((err) => {
				uni.showModal({
				  content: err.message || '请求服务失败',
				  showCancel: false
				})
			  })
		  }
	  }
    }
  }
</script>

